package com.aca.market.controller;

import com.aca.market.entity.IndentItem;
import com.aca.market.entity.Item;
import com.aca.market.entity.Storage;
import com.aca.market.service.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentMap;
import java.util.stream.Collectors;

@Slf4j
@Controller
public class IndentItemController {

    @Autowired
    IIndentItemService iiService;
    @Autowired
    ICatalogService catalogService;
    @Autowired
    IPermissionService permissionService;
    @Autowired
    IUserService userService;
    @Autowired
    IIndentService indentService;
    @Autowired
    IItemService itemService;
    @Autowired
    IStorageService storageService;
    @Autowired
    ICartService cartService;

    @GetMapping("/dashboard")
    public String toDashBoard(Model model){
        //鉴权 不在这弄了 放shiro里
//        if (!permissionService.hasPermToDashBoard()) return "no-auth";
        userService.nowSession().setAttribute("notice",storageService.checkStorage());
        List<IndentItem> indentItems = iiService.list();
        log.info("==========indentItems: " + indentItems);
        Map<Long,String> typeName = catalogService.typeIdNameMap(indentItems);
        model.addAttribute("typeName",typeName);
        model.addAttribute("indents",indentItems);
        model.addAttribute("monthProfit",iiService.getMonthProfit());  //收入
        model.addAttribute("monthNetProfile",iiService.getMonthNetProfile());  //利润
        model.addAttribute("monthPurchaseCost",iiService.getMonthPurchaseCost());  //成本
        model.addAttribute("monthLoss",iiService.getLoss());  //损耗
        if (userService.nowUser()!=null){
            model.addAttribute("cart",cartService.getUserCart());
        }
        return "dashboard";
    }

    @GetMapping("/dashboard/indentsChart")
    @ResponseBody
    public ConcurrentMap<String,Integer> getIndents(){
        ConcurrentMap<String,Integer> monthIndents= indentService.getMonthlyIndents();
        log.info("================getIndents{}",monthIndents);
        return monthIndents;
    }


    @GetMapping("/dashboard/bestSellItems")
    @ResponseBody
    public ConcurrentMap<String,Integer> getBestSellItems(){
        return iiService.getBestSellerItem();
    }


    @GetMapping("/dashboard/indents")
    public String filterIndents(@RequestParam(defaultValue = "1") Integer pageNum,
                                @RequestParam(required = false) String name,
                                @RequestParam(required = false) Boolean salesDesc,
                                @RequestParam(required = false) LocalDateTime start,
                                @RequestParam(required = false) LocalDateTime end,
                                @RequestParam(required = false,name = "typeIdList[]") List<Long> typeIdList,
                                Model model){
        Page<IndentItem> page = new Page(pageNum,16);
        boolean typesFlag = typeIdList != null && (!typeIdList.isEmpty());
        List<IndentItem> indentItems = iiService.selectPage(page,new QueryWrapper<IndentItem>()
                .between(start!=null&&end!=null,"create_time", start, end)
                .in(typesFlag,"item_type", typeIdList)
                .like(name!=null&&!name.trim().isEmpty(),"item_name",name)
                .orderByDesc(salesDesc!=null&&salesDesc,"count"))
                .getRecords();
        Map<Long,String> types = catalogService.getAllIdNameMap();
        model.addAttribute("types",types);
        model.addAttribute("page",page);
        model.addAttribute("indentItems",indentItems);
        model.addAttribute("monthProfit",iiService.getMonthProfit());  //收入
        model.addAttribute("monthNetProfile",iiService.getMonthNetProfile());  //利润
        model.addAttribute("monthPurchaseCost",iiService.getMonthPurchaseCost());  //成本
        //model.addAttribute("monthLoss",(float) ((int)(Math.random()*(50000-10000)+10000))/100);  //损耗
        model.addAttribute("monthLoss",iiService.getLoss());  //损耗
        if (userService.nowUser()!=null){
            model.addAttribute("cart",cartService.getUserCart());
        }
        return "indent-sale";
    }

    @GetMapping("/dashboard/stock")
    public String filterStock(@RequestParam(defaultValue = "1") Integer pageNum,
                                @RequestParam(required = false) LocalDateTime start,
                                @RequestParam(required = false) LocalDateTime end,
                                @RequestParam(required = false) String name,
                                @RequestParam(required = false) Long itemId,
                                @RequestParam(required = false,name = "typeIdList[]") List<Long> typeIdList,
                                Model model){
        Page<Storage> page = new Page(pageNum,16);
        boolean typesFlag = typeIdList != null && (!typeIdList.isEmpty());
        List<Long> itemIdList = itemService.list(new QueryWrapper<Item>()
                .select("id")
                .in(typesFlag, "type", typeIdList))
                .parallelStream().map(item -> item.getId()).collect(Collectors.toList());
        List<Storage> storages = storageService.selectPage(page, new QueryWrapper<Storage>()
//                .select("item_id","item_name","inventory","price_in","sales","purchase","create_time","update_time")
                .in(!itemIdList.isEmpty(), "item_id", itemIdList)
                .like(!(name == null || name.trim().isEmpty()), "item_name", name)
                .between(start != null && end != null, "update_time", start, end)
                .eq(itemId != null, "item_id", itemId)).getRecords();
        //要用itemId:TypeName的map
        Map<Long,String> itemIdTypeNameMap = catalogService.getItemIdTypeNameMap();
        Map<Long,String> types = catalogService.getAllIdNameMap();
        model.addAttribute("types",types);
        model.addAttribute("page",page);
        model.addAttribute("idNameMap",itemIdTypeNameMap);
        model.addAttribute("storages",storages);
        model.addAttribute("monthProfit",iiService.getMonthProfit());  //收入
        model.addAttribute("monthNetProfile",iiService.getMonthNetProfile());  //利润
        model.addAttribute("monthPurchaseCost",iiService.getMonthPurchaseCost());  //成本
        model.addAttribute("monthLoss",iiService.getLoss());  //损耗
        if (userService.nowUser()!=null){
            model.addAttribute("cart",cartService.getUserCart());
        }
        return "stock";
    }

    @GetMapping("/dashboard/pick")
//    @ResponseBody
    public String filterPickItems(@RequestParam(defaultValue = "1") Integer pageNum,
                                   @RequestParam(required = false) LocalDateTime start,
                                   @RequestParam(required = false) LocalDateTime end,
                                   @RequestParam(required = false) Long itemId,
                                   @RequestParam(required = false) String name,
                                   @RequestParam(required = false,name = "typeIdList[]") List<Long> typeIdList,
                                   Model model){
        Page<Item> page = new Page(pageNum,8);
        Map<Long,String> types = catalogService.getAllIdNameMap();
        List<Item> items = itemService.selectItemPage(page, new QueryWrapper<Item>()
                .between(start != null && end != null, "created_time", start, end)
                .like(!(name == null || name.trim().isEmpty()), "name", name)
                .in(typeIdList != null && !typeIdList.isEmpty(), "type", typeIdList)
                .eq(itemId != null, "id", itemId))
                .getRecords();

        if (userService.nowUser()!=null){
            model.addAttribute("cart",cartService.getUserCart());
        }
        model.addAttribute("items",items);
        model.addAttribute("page",page);
        model.addAttribute("types",types);
        return "item-pick";
    }

    @GetMapping("/dashboard/cart")
    public String toCashierSubtotal(){
        return "redirect:/cart";
    }

    @GetMapping("/dashboard/typeItems")
    //没做时间
    public String typeItemSales(@RequestParam(defaultValue = "1") Integer pageNum,
                                @RequestParam(required = false) Boolean salesDesc,
                                @RequestParam(required = false,name = "typeIdList[]") List<Long> typeIdList,
                                Model model){
        Page<IndentItem> page = new Page(pageNum,16);
        List<IndentItem> indentItems;
        indentItems = salesDesc==null?
                 iiService.getTypeItemSale(typeIdList,false)
                :iiService.getTypeItemSale(typeIdList,salesDesc);
        model.addAttribute("types",catalogService.getAllIdNameMap());
        model.addAttribute("page",page);
        model.addAttribute("indentItems",indentItems);
        model.addAttribute("monthProfit",iiService.getMonthProfit());  //收入
        model.addAttribute("monthNetProfile",iiService.getMonthNetProfile());  //利润
        model.addAttribute("monthPurchaseCost",iiService.getMonthPurchaseCost());  //成本
        model.addAttribute("monthLoss",iiService.getLoss());  //损耗
        if (userService.nowUser()!=null){
            model.addAttribute("cart",cartService.getUserCart());
        }
        return "indent-sale-type";
    }

    //xg
    @GetMapping("/dashboard/loss")
    public String typeItemLoss(@RequestParam(required = false,name = "typeIdList[]") List<Long> typeIdList,
                               @RequestParam(required = false) LocalDateTime start,
                               @RequestParam(required = false) LocalDateTime end,
                               @RequestParam(required = false) String name,
                               Model model){
        List<Item> items = itemService.list(new QueryWrapper<Item>()
                .between(end!=null&&start!=null,"updated_time",start,end)
                .in(typeIdList!=null&&!typeIdList.isEmpty(),"type",typeIdList)
                .like(name!=null&&!name.trim().isEmpty(),"name",name)
                .eq("status","-1"));
        model.addAttribute("items",items);
        model.addAttribute("types",catalogService.getAllIdNameMap());
        model.addAttribute("monthProfit",iiService.getMonthProfit());  //收入
        model.addAttribute("monthNetProfile",iiService.getMonthNetProfile());  //利润
        model.addAttribute("monthPurchaseCost",iiService.getMonthPurchaseCost());  //成本
        model.addAttribute("monthLoss",iiService.getLoss());  //损耗
        if (userService.nowUser()!=null){
            model.addAttribute("cart",cartService.getUserCart());
        }
        return "loss";
    }
}
